package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

/**
 * @author: dangwen
 * @createDate: 2021/1/21
 */
@Configuration
@EnableAuthorizationServer // 开启授权服务器的功能
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    public PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsServiceBean;
//    @Autowired
//    private RedisConnectionFactory redisConnectionFactory;

    /**
     * 配置第三方客户端
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("coin-api")
                .secret(passwordEncoder.encode("coin-secret")).scopes("all")
                .authorizedGrantTypes("password", "refresh").accessTokenValiditySeconds(24 * 7200)
                .refreshTokenValiditySeconds(7 * 24 * 7200);
        super.configure(clients);
    }

    /**
     * 设置授权管理器和  UserDetailsService
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // token存放在内存中，多实例的情况下，会有数据共享问题，所以我们存放在redis，解决共享问题
//        endpoints.tokenStore(new InMemoryTokenStore())
//                .authenticationManager(authenticationManager) .userDetailsService(userDetailsServiceBean) ;
//        endpoints.authenticationManager(authenticationManager) .userDetailsService(userDetailsServiceBean)
//                .tokenStore(redisTokenStore());
        endpoints.authenticationManager(authenticationManager) .userDetailsService(userDetailsServiceBean)
                .tokenStore(jwtTokenStore()).tokenEnhancer(jwtAccessTokenConverter());
        super.configure(endpoints);
    }

    /**
     * 不再使用redis作为存储token的容器
     */
//    private TokenStore redisTokenStore(){
//        return new RedisTokenStore(redisConnectionFactory);
//    }

    public TokenStore jwtTokenStore(){
        JwtTokenStore jwtTokenStore = new JwtTokenStore(jwtAccessTokenConverter());
        return jwtTokenStore;
    }
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        // 读取  classpath 下面的密钥文件
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        // 获取  KeyStoreFactory
        ClassPathResource classPathResource = new ClassPathResource("coin-exchange.jks");
        // 给  JwtAccessTokenConverter 设置一个密钥对
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "coin-exchange".toCharArray());
        tokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("coin-exchange", "coin-exchange".toCharArray()));
        return tokenConverter;
    }
}
